package com.example.echoewish.ui.main_activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.echoewish.pojo.Post;
import com.example.echoewish.R;
import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PublishFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PublishFragment extends Fragment {

    private Uri imageUri=null;
    EditText titleEditText;
    EditText contentEditText;
    Button selectImageButton;
    ImageView selectedImageView;
    Button deleteImageButton;
    EditText rewardEditText;
    Button publishButton;
    List<Button> tabButtonList=new LinkedList<>();


    String zone="未选择";
    File outputImage=null;

    LoadingDialog loadingDialog=null;

    private PublishViewModel publishViewModel;

    public  Handler mainHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.d("test_activity", "handleMessage: ");
            switch (msg.what)
            {
                case Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE:
                    loadingDialog.loadSuccess();
                    break;
                case Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE:
                    loadingDialog.loadFailed();
                    break;
            }
        }
    };

    public PublishFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static PublishFragment newInstance() {
        PublishFragment fragment = new PublishFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_publish, container, false);
        initViewModel();
        observeLiveData();
        //获取所有控件
        tabButtonList.add(view.findViewById(R.id.publish_tab_button1));
        tabButtonList.add(view.findViewById(R.id.publish_tab_button2));
        tabButtonList.add(view.findViewById(R.id.publish_tab_button3));
        tabButtonList.add(view.findViewById(R.id.publish_tab_button4));
        tabButtonList.add(view.findViewById(R.id.publish_tab_button5));

        titleEditText=view.findViewById(R.id.publish_title_edit_text);
        contentEditText=view.findViewById(R.id.publish_content_edit_text);
        selectedImageView=view.findViewById(R.id.publish_selected_image_view);
        deleteImageButton=view.findViewById(R.id.publish_delete_image_button);
        selectImageButton=view.findViewById(R.id.publish_select_image_button);
        rewardEditText=view.findViewById(R.id.publish_reward_edit_text);
        publishButton=view.findViewById(R.id.publish_publish_button);
        loadingDialog=new LoadingDialog(this.getActivity()).setLoadingText("发布中");
        loadingDialog.setLoadingText("发布中")
                .setSuccessText("发布成功")//显示加载成功时的文字
                .setFailedText("发布失败")
                .setInterceptBack(true);

        for(Button button:tabButtonList)
        {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for(Button button:tabButtonList)
                        button.setBackground(getResources().getDrawable(R.drawable.zone_tab_button_noselected));
                    button.setBackground(getResources().getDrawable(R.drawable.zone_tab_button_selected));
                    zone=button.getText().toString();
                }

            });
        }

        selectImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showBottomDialog();
            }
        });

        deleteImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedImageView.setImageBitmap(null);
                selectedImageView.setVisibility(View.GONE);
                selectImageButton.setVisibility(View.VISIBLE);
                deleteImageButton.setVisibility(View.GONE);
            }
        });

        publishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             String title=titleEditText.getText().toString();
             String content =contentEditText.getText().toString();
             String reward=rewardEditText.getText().toString();
             Date time=new Date();
             SimpleDateFormat simpleDateFormat=new SimpleDateFormat(Constant.FILE_NAME_OR_COMMENT_FORMAT);
             String nowTime=simpleDateFormat.format(time);
            SimpleDateFormat filenameDateFormat=new SimpleDateFormat(Constant.FILE_NAME_OR_COMMENT_FORMAT);
            String fileTime=filenameDateFormat.format(time);
            fileTime=fileTime.replace(' ','-');
            fileTime=fileTime.replace(':','-');
             String filename=fileTime+ UserInfo.getInstance().UserId+".jpg";

             Log.d("test_activity", "onClick: "+filename);

             if(zone.equals("未选择"))
             {
                 Toast.makeText(getActivity(),"分区还未选择",Toast.LENGTH_LONG).show();
                 return;
             }
             if(title.equals(""))
             {
                 Toast.makeText(getActivity(),"标题不能为空",Toast.LENGTH_LONG).show();
                 return;
             }
             else if(title.equals(""))
             {
                 Toast.makeText(getActivity(),"内容不能为空",Toast.LENGTH_LONG).show();
                 return;
             }
             else if(UserInfo.getInstance().UserId==-1)
             {
                 Toast.makeText(getActivity(),"未登录，不能发布帖子",Toast.LENGTH_LONG).show();
                 return;
             }

            Post post=new Post(UserInfo.getInstance().UserId,title,zone,content,reward,filename,nowTime);
             publishViewModel.postMutableLiveData.setValue(post);
             clear();
             loadingDialog.show();
            }
        });
        return view;
    }

    private void clear()
    {
        String zone="未选择";
        titleEditText.setText("");
        contentEditText.setText("");
        selectedImageView.setImageBitmap(null);
        rewardEditText.setText("");
        outputImage=null;
        selectedImageView.setVisibility(View.GONE);
        selectImageButton.setVisibility(View.VISIBLE);
        deleteImageButton.setVisibility(View.GONE);
    }

    private void initViewModel()
    {
        publishViewModel=new ViewModelProvider(requireActivity(),new ViewModelProvider.AndroidViewModelFactory(getActivity().getApplication())).get(PublishViewModel.class);
    }

    private void observeLiveData()
    {
        publishViewModel.postMutableLiveData.observe(this, new Observer<Post>() {
            @Override
            public void onChanged(Post post) {
                publishViewModel.publishPost(outputImage);
            }
        });

        publishViewModel.responseMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (s.equals(Constant.HTTPS_GET_CALLBACK_SUCCESS)) {
                    Message message = new Message();
                    message.what = Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                    mainHandler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.what = Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE;
                    mainHandler.sendMessage(message);
                    Log.d(Constant.CALLBACK_TAG, "发布post回调成功");
                }
            }
        });
    }

    //函数作用 显示底部对话框 以及配置好底部对话框的点击事件
    private void showBottomDialog()
    {
        Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.button_dialog, null);
        TextView takePicturesTextView=contentView.findViewById(R.id.bottom_dialog_take_pictures);
        TextView selectAlbumTextView=contentView.findViewById(R.id.bottom_dialog_from_album);

        takePicturesTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                outputImage= new File(getActivity().getExternalCacheDir(),String.valueOf(System.currentTimeMillis())+".jpg");
                if(outputImage.exists())
                    outputImage.delete();
                try {
                    outputImage.createNewFile();
                }
                catch (Exception e)
                {

                }
                imageUri= FileProvider.getUriForFile(getActivity(),"com.example.echoewish.fileprovider",outputImage);
                Intent cameraIntent=new Intent("android.media.action.IMAGE_CAPTURE");
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(cameraIntent, Constant.TO_CAMERA_ACTIVITY);
            }
        });


        selectAlbumTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent albumIntent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
                albumIntent.addCategory(Intent.CATEGORY_OPENABLE);
                albumIntent.setType("image/*");
                startActivityForResult(albumIntent, Constant.TO_ALBUM_ACTIVITY);
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case Constant.TO_CAMERA_ACTIVITY:
                if(resultCode== Activity.RESULT_OK)
                try {
                    selectedImageView.setImageBitmap(BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri)));
                    selectedImageView.setVisibility(View.VISIBLE);
                    deleteImageButton.setVisibility(View.VISIBLE);
                    selectImageButton.setVisibility(View.INVISIBLE);

                }
                catch (Exception e)
                {

                }

                break;
            case Constant.TO_ALBUM_ACTIVITY:
                if(resultCode== Activity.RESULT_OK&&data!=null)
                {
                    try {
                        Bitmap bitmap= BitmapFactory.decodeFileDescriptor(getActivity().getContentResolver().openFileDescriptor(data.getData(),"r").getFileDescriptor());
                        selectedImageView.setImageBitmap(bitmap);
                        outputImage= new File(getActivity().getExternalCacheDir(),String.valueOf(System.currentTimeMillis())+".jpg");
                        if(outputImage.exists())
                            outputImage.delete();
                        try {
                            outputImage.createNewFile();
                        }
                        catch (Exception e)
                        {

                        }
                        try {
                            outputImage.createNewFile();
                            FileOutputStream fileOutputStream = new FileOutputStream(outputImage);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        selectedImageView.setVisibility(View.VISIBLE);
                        deleteImageButton.setVisibility(View.VISIBLE);
                        selectImageButton.setVisibility(View.INVISIBLE);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }
                break;

        }
    }
}